// 获取历史信息
var mongoose = require('mongoose');
var stock = require('tushare').stock;
var async = require('async');
var util = require('../util');
var model = require('../model');

var logger = require('../util/log').test;

var list = model.list;
var history = model.history;

mongoose.set('debug', false);

function change2Obj(code, ktype, arr) {
    var obj = {};
    obj.id = code + ':' + arr[0];
    obj.ktype = ktype;
    obj.code = code;
    obj.date = arr[0];
    obj.open = arr[1];
    obj.highest = arr[2];
    obj.close = arr[3];
    obj.lowest = arr[4];
    obj.vol = arr[5];
    obj.priceChange = arr[6];
    obj.changeRate = arr[7];
    obj.ma5 = arr[8];
    obj.ma10 = arr[9];
    obj.ma20 = arr[10];
    obj.vo5 = arr[11];
    obj.vo10 = arr[12];
    obj.vo20 = arr[13];
    obj.tor = arr[14];

    return obj;
}

function record(code, ktype, callback) {
    let options = {
        code,
        ktype
    };
    stock.getHistory(options).then(({ data }) => {
        if (data && data.record && data.record.length > 0) {
            console.log('code: %s, have %d record!', code, data.record.length);
            let count = 0;
            async.eachLimit(data.record, 3, (his, cb) => {
                let date = his[0];
                let id = code + ':' + ktype + ':' + date;

                let upsertOpt = { new: true, upsert: true };

                history.findOneAndUpdate({ id }, change2Obj(code, ktype, his), upsertOpt, (err, doc, res) => {
                    if (err) return cb(err);
                    count++;
                    cb();
                });
            }, err => {
                if (err) return console.log('err: ', err) && callback(err);
                console.log('code: %s, add %d history record!', code, count);
                setTimeout(function() {
                    callback();
                }, 200);
                // callback();
            });
        } else {
            logger.warn('code: %s didn\'t have any records!', code, options);
            setTimeout(function () {
                callback();
            }, 200);
        }
    });
}

function sync(ktype) {

    let codes = [];

    list.find().sort('code').exec((err, res) => {
        // console.log(res.length);

        for (let stock of res) {
            codes.push(stock.code); // 所有的股票代码
        }

        async.eachLimit(codes, 3, (code, cb) => {
            console.log({ ktype });
            record(code, ktype, cb);
        }, err => {
            if (err) return logger.error(err);
            mongoose.disconnect();
        });
    });
}

exports.sync = sync;

sync('week');